# !/usr/bin/ruby -w
# -*- coding: UTF-8 -*-

require 'shell'
require "pathname"
require "Spaceship"

class SuperSignature
    attr_accessor :apple_id_name
    attr_accessor :apple_id_pwd
    attr_accessor :user_udid
    attr_accessor :app_id
    attr_accessor :app_path
    attr_accessor :output_path

    attr_accessor :app_name
    attr_accessor :app_bundle

    def initialize(apple_id_name, apple_id_pwd, user_udid, app_id, app_path, output_path)
        @apple_id_name = apple_id_name
        @apple_id_pwd = apple_id_pwd
        @app_id = app_id
        @user_udid = user_udid
        @app_path = app_path
        @output_path = output_path
    end

    def prepare_func
        @app_name = @app_id + '.ipa'
        @app_bundle = @apple_id_name.gsub('@', '.') + '.' + @app_id
        # copy ipa
        FileUtils.mkdir_p(@output_path) unless File.exists?(@output_path)
        FileUtils.cp(@app_path, @output_path + '/' + @app_name)
    end

    def run_func
        result = true
        begin
            prepare_func
            login_func
            check_certificate_func
            check_identifier_func
            check_device_func
            check_profile_func

            register_cert_func
            signature_func
        rescue
            result = false
            puts("发生错误！！!")
            puts(-1)
        end

        if result == true
            puts(0)
        end
    end

    def login_func
        Spaceship::Portal.login(@apple_id_name, @apple_id_pwd)
    end

    def check_certificate_func
        cert = Spaceship.certificate.production.all.first
        if cert == nil
            csr, pkey = Spaceship::Portal.certificate.create_certificate_signing_request
            cert = Spaceship::Portal.certificate.production.create!(csr: csr)
        end
        fileName = @app_id + ".cer"
        File.write(@output_path + '/' + fileName, cert.download)
    end

    def check_identifier_func
        app = Spaceship::Portal.app.find(@app_bundle)
        if app == nil
            app = Spaceship.app.create!(bundle_id: @app_bundle, name: @app_id)
        end
    end

    def check_device_func
        device = Spaceship::Portal.device.find_by_udid(@user_udid, include_disabled: true)
        if device == nil
            puts("Create udid by " + @user_udid)
            time = Time.new
            timeDesc =  time.strftime("%Y-%m-%d %H:%M:%S")
            user_name = timeDesc + " " + "#{rand(10..1000)}"
            device = Spaceship::Portal.device.create!(name: user_name, udid: @user_udid)
        else
            puts("Find udid by " + @user_udid)
            device.enable!
        end
    end

    def check_profile_func
        profile = Spaceship::Portal.provisioning_profile.ad_hoc.find_by_bundle_id(bundle_id: @app_bundle).first
        if profile == nil
            cert = Spaceship.certificate.production.all.first
            profile = Spaceship::Portal.provisioning_profile.ad_hoc.create!(bundle_id: @app_bundle, certificate: cert)
        end
        fileName = @app_id + ".mobileprovision"
        File.write(@output_path + '/' + fileName, profile.download)
    end

    def register_cert_func
        # system "echo \'fastlane fastlane-credentials add --username #{@apple_id_name}  --password #{@apple_id_pwd}\'"
        # system "echo \'fastlane cert --username #{@apple_id_name}\'"
    end

    def signature_func
        app_file = @output_path + @app_name
        profile_file = @output_path + '/' + @app_id + '.mobileprovision'
        cert = Spaceship.certificate.production.all.first
        signing_identity = cert.name.gsub('iOS', 'iPhone') + ': ' + cert.owner_name + " " + "(#{cert.owner_id})"

        puts("app_file="+app_file)
        puts('profile_file='+profile_file)

        system "echo \'fastlane sigh resign #{app_file} --signing_identity \"#{signing_identity}\" -p #{profile_file}\'"
    end
end

# APPLE_ID_USER = "KennethSWrigh@gmail.com"
# APPLE_ID_PWD = "Nerfa561"
# APP_ID = "MyApp1"
# # USER_UDID = "00008020-000908EC0EF2002E"

# APPLE_ID_USER="KennethSWrigh@gmail.com" APPLE_ID_PWD="Nerfa561" APP_ID="MyApp1" USER_UDID="00008020-000908EC0EF2002E" ruby resign.rb
# APPLE_ID_USER = ENV['APPLE_ID_USER']
# APPLE_ID_PWD = ENV['APPLE_ID_PWD']
# APP_ID = ENV['APP_ID']
# USER_UDID = ENV['USER_UDID']

# ruby resign.rb KennethSWrigh@gmail.com Nerfa561 MyApp1 00008020-000908EC0EF2002E
APPLE_ID_USER = ARGV[0]
APPLE_ID_PWD = ARGV[1]
USER_UDID = ARGV[2]
APP_ID = ARGV[3]
APP_PATH = ARGV[4]
OUTPUT_PATH = ARGV[5]

signature = SuperSignature.new(APPLE_ID_USER, APPLE_ID_PWD, USER_UDID, APP_ID, APP_PATH, OUTPUT_PATH)
signature.run_func


